package com.pwser.service;

import com.pwser.pojo.JDGood;
import com.pwser.utils.ESUtil;
import com.pwser.utils.JDHtmlParseUtil;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ElasticSearchService {

    /**
     * 查询全部数据
     * @param page
     * @return
     * @throws IOException
     */
    public List<JDGood> searchAll(int page) throws IOException {
        List<Map<String, Object>> MapList = ESUtil.matchAll(page);
        List<JDGood> jdGoodList = this.translateMapList(MapList);
        return jdGoodList;
    }

    /**
     * 关键字查询数据
     * @param keyword
     * @param page
     * @return
     * @throws IOException
     */
    public List<JDGood> searchByKeyword(String keyword, int page) throws IOException {
        List<Map<String, Object>> MapList = ESUtil.match("title", keyword, page);
        List<JDGood> jdGoodList = this.translateMapList(MapList);
        return jdGoodList;
    }

    /**
     * 爬取京东数据
     * @param keyword
     * @return
     * @throws IOException
     */
    public Boolean parseJD(String keyword) throws IOException {
        List<JDGood> jdGoodList = JDHtmlParseUtil.getJDSearchContentByKeyword(keyword);
        Boolean bulkSuccess = ESUtil.bulkAddDocuments(jdGoodList);
        return bulkSuccess;
    }

    /**
     * 转换数据
     * @param MapList
     * @return
     */
    private List<JDGood> translateMapList(List<Map<String, Object>> MapList) {
        List<JDGood> jdGoodList = new ArrayList<>();
        for (Map<String, Object> map : MapList) {
            JDGood jdGood = new JDGood();
            jdGood.setTitle(map.get("title").toString());
            jdGood.setPrice(Float.parseFloat(map.get("price").toString()));
            jdGood.setImg(map.get("img").toString());
            jdGood.setHighlight(map.get("highlight")!=null?map.get("highlight").toString():"");
            jdGoodList.add(jdGood);
        }
        return jdGoodList;
    }
}
